package longrise.phone.com.bjjt_henan.compensate;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longrise.bjjt.util.FileUtils;
import com.longrise.bjjt.util.StringUtils;
import com.longrise.bjjt.util.UiUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;

import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.PermissionHelper;


@SuppressLint("HandlerLeak")
@SuppressWarnings("deprecation")
public class HeNanSurfaceViewCameraActivity extends Activity implements OnTouchListener, OnClickListener {

    public int resultCode = 110;
    boolean flashFlag = true;
    private float focusX;
    private float focusY;
    private Bitmap focus_bitmap;
    private boolean safeToTakePicture = false;
    private RelativeLayout fl_sv;// 显示对焦图片和提示图片的根布局
    private ImageView imageBox;// 对焦图片
    private ImageView iv_flash;// 闪光灯图片
    private ImageView iv_frame;// 拍照中间提示图片
    private ImageView iv_photo;// 拍照按钮
    private Camera mCamera;// 照相机
    private SurfaceHolder mHolder;

    private int midX;
    private int midY;

    private SurfaceView sv_camera;// 相机界面
    private ImageView tv_return;// 返回按钮
    private TextView tv_title;// 提示拍照主题
    private TextView tv_title_bottom;

    private Bundle mBundle;

    private String title;//标题

    private String titleBottom;//标题下面下提示

    private int backGroundResourceId; //背景图片id

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    if (imageBox != null) { // 隐藏对焦图片
                        imageBox.setAlpha(0.0F);
                        if (fl_sv != null) {
                            fl_sv.removeView(imageBox);
                        }
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };
    private String absolutePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
        // WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.custome_camera_layout);
        initView();
        initdata();

    }

    /**
     * 初始化数据界面
     */

    private void initdata() {
        Intent localIntent = getIntent();
        if (localIntent != null) {
            mBundle = localIntent.getExtras();
            if (null != mBundle) {
                title = mBundle.getString("title");//顶部标题
                titleBottom = mBundle.getString("titleBottom");//标题下小提示
                backGroundResourceId = mBundle.getInt("backGroundResourceId", 0);//图片资源

                if (StringUtils.isEmpty(title)) {
                    title = "";
                }

                if (StringUtils.isEmpty(titleBottom)) {

                }
                titleBottom = "";

                tv_title.setText(title);
                tv_title_bottom.setText(titleBottom);

                if (backGroundResourceId != 0) {
                    iv_frame.setVisibility(View.VISIBLE);
                    iv_frame.setImageResource(backGroundResourceId);
                } else {
                    iv_frame.setVisibility(View.GONE);
                }
            }

        }
    }

    private void initView() {
        WindowManager localWindowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics localDisplayMetrics = new DisplayMetrics();

        localWindowManager.getDefaultDisplay().getMetrics(localDisplayMetrics);
        this.setMidX((localDisplayMetrics.widthPixels / 2));
        this.setMidY((localDisplayMetrics.heightPixels / 2));

        this.fl_sv = ((RelativeLayout) findViewById(R.id.fl_sv));
        this.tv_title = ((TextView) findViewById(R.id.tv_title));
        this.tv_title_bottom = ((TextView) findViewById(R.id.tv_title_bottom));
        this.iv_frame = ((ImageView) findViewById(R.id.iv_frame));
        this.iv_photo = ((ImageView) findViewById(R.id.iv_photo));
        this.iv_flash = ((ImageView) findViewById(R.id.iv_flash));
        this.tv_return = ((ImageView) findViewById(R.id.tv_return));
        this.sv_camera = ((SurfaceView) findViewById(R.id.sv_camera));
        fl_sv.setOnTouchListener(this);
        this.iv_photo.setOnClickListener(this);
        this.iv_flash.setOnClickListener(this);
        this.tv_return.setOnClickListener(this);

        this.mHolder = this.sv_camera.getHolder();
        this.mHolder.addCallback(new SurfaceHolder.Callback() {

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                releasecamera();
            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                try {
                    mCamera = Camera.open();
                    if (mCamera == null) { // 提示用户打开权限
                        showAlertDialog(getString(R.string.crmerastate));
                        return;

                    }
                    initCamera();
                } catch (Exception e) {
                    e.printStackTrace();
                    showAlertDialog(getString(R.string.crmerastate));

                }

            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                CameraAutoForcus();
            }
        });
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    /**
     * 初始化摄像头参数，并展开预览界面
     */
    @SuppressLint("InlinedApi")
    protected void initCamera() {
        try {
            if (null != mCamera) {
                // 获取相机的参数
                Parameters param = mCamera.getParameters();
                param.setPreviewSize(640, 480); // 预览尺寸,注意要在摄像头支持的范围内选择
                param.setPictureSize(640, 480); // 照片尺寸,注意要在摄像头支持的范围内选择
                //List<Camera.Size> previewSizes = param.getSupportedPreviewSizes();
                 /* for (Camera.Size size :previewSizes) {
                    Log.e("ly" , "width :" + size.width + " height :" + size.width);
                }*/
                //List<Camera.Size> pictureSizes = param.getSupportedPictureSizes();
                /*for (Camera.Size size :pictureSizes) {
                    Log.e("ly" , "width :" + size.width + " height :" + size.width);
                }*/
                param.setJpegQuality(100); // 设置相片质量
                param.setPictureFormat(PixelFormat.JPEG);
                param.setFlashMode(Parameters.FLASH_MODE_OFF);
                if (param.getSupportedFocusModes().contains(Parameters.FOCUS_MODE_AUTO)) {
                    param.setFocusMode(Parameters.FOCUS_MODE_AUTO);// FOCUS_MODE_CONTINUOUS_PICTURE

                }
                mCamera.setParameters(param); // 设置相机参数
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();// 打开预览界面
                safeToTakePicture = true;
                if (mCamera != null) {
                    mCamera.cancelAutoFocus();

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            releasecamera();
            showAlertDialog(getString(R.string.crmerastate));
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (mCamera == null) {
            return false;

        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                focusX = event.getX();
                focusY = event.getY();
                startFocus(focusX, focusY);
                break;

        }

        return true;
    }

    /**
     * 对焦显示图片效果
     *
     * @param focusX2
     * @param focusY2
     */
    private void startFocus(float focusX2, float focusY2) {
        if (this.imageBox != null) {
            this.fl_sv.removeView(this.imageBox);
            this.imageBox = null;
        }
        this.imageBox = new ImageView(this);
        // 获取对焦的模型图片Bitmap
        this.focus_bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.touch_focus);
        this.imageBox.setImageBitmap(this.focus_bitmap);
        this.imageBox.setAlpha(0.0F);
        this.imageBox.setX(focusX2 - this.focus_bitmap.getWidth() / 2);
        this.imageBox.setY(focusY2 - this.focus_bitmap.getHeight() / 2);
        this.imageBox.setAlpha(1.0F);
        this.fl_sv.addView(this.imageBox);
        CameraAutoForcus();// 点击对焦一下
        mHandler.sendEmptyMessageDelayed(1, 2000);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_photo:
                if (safeToTakePicture) { // 停止预览
                    TakeAndSavePicture();
                    safeToTakePicture = false;
                }
                break;
            case R.id.iv_flash:
                try {
                    if (flashFlag) {
                        iv_flash.setSelected(true);
                        if (null != mCamera) {
                            Parameters parameters = mCamera.getParameters();
                            parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
                            mCamera.setParameters(parameters);
                        }

                        flashFlag = false;
                    } else {
                        iv_flash.setSelected(false);
                        if (null != mCamera) {
                            Parameters parameters = mCamera.getParameters();
                            parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
                            mCamera.setParameters(parameters);
                        }
                        flashFlag = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    UiUtil.showToast(HeNanSurfaceViewCameraActivity.this, "对不起没有获取到您设备的闪光灯，请直接拍照");
                }

                break;

            case R.id.tv_return:// 退出按钮
                HeNanSurfaceViewCameraActivity.this.finish();

                break;
        }
    }

    /**
     * 保存图片信息
     */
    private void TakeAndSavePicture() {
        // 隐藏焦点图片
        if (this.imageBox != null) {
            this.imageBox.setAlpha(0.0F);
            if (this.fl_sv != null) {
                this.fl_sv.removeView(this.imageBox);
            }
        }

        if (this.mCamera == null) { // 若相机为null跳出
            return;
        }

        // 开始拍照，并返回拍照信息
        mCamera.takePicture(new ShutterCallback() {//开始拍照卡死 TODO

            @Override
            public void onShutter() {

            }
        }, null, new MyPictureCallBack());

    }

    /**
     * 提示用户打开摄像头权限
     *
     * @param string
     */
    protected void showAlertDialog(String string) {
        PermissionHelper.showPermissionDialog(this, string, true);
    }

    /**
     * 自动对焦
     */
    private void CameraAutoForcus() {
        if (null != mCamera) {
            mCamera.autoFocus(new AutoFocusCallback() {

                @Override
                public void onAutoFocus(boolean success, Camera camera) {
                    if (success) {
                        if (mCamera != null) {
                            mCamera.cancelAutoFocus();
                        }

                    }
                }
            });

        }

    }

    // 相片拍摄完成时调用
    class MyPictureCallBack implements PictureCallback {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            boolean b = SavePicturetoSdcard(data);
            if (b) {
                sendImage(absolutePath);
            }
            mCamera.startPreview();// 拍完照后重新开始预览
            safeToTakePicture = true;
        }

    }

    // 保存相片到sdcard
    public boolean SavePicturetoSdcard(byte[] data) {
        boolean success = false;
        try {
            if ((data != null) && (!data.equals("")) && (data.length > 0)) {
                String dir = FileUtils.getDir("KCKP", HeNanSurfaceViewCameraActivity.this);
                if (TextUtils.isEmpty(dir)) {
                    PermissionHelper.showPermissionDialog(this, getResources().getString(R.string.storgestate), true);
                    return false;
                }
                File file = new File(dir, FileUtils.dateformaterfilename());

                absolutePath = file.getAbsolutePath();//照片的存储路径
                boolean writeFileissuccess = FileUtils.writeFile(data, absolutePath, false);// 将文件写入到SD卡下
                success = writeFileissuccess;
                return success;
            }
        } catch (Exception e) {
            e.printStackTrace();
            UiUtil.showToast(HeNanSurfaceViewCameraActivity.this, "照片拍摄出错请重新拍此张照片");

            success = false;
        }
        return success;
    }

    /**
     * 当销毁时 释放资源
     */
    private void releasecamera() {

        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
            System.gc();

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (this.focus_bitmap != null) {
            this.focus_bitmap.recycle();
            this.focus_bitmap = null;
        }
        if (this.iv_frame != null) {
            this.iv_frame = null;
        }
        if (this.mCamera != null) {
            releasecamera();
            this.mCamera = null;
        }

        System.gc();

    }

    @Override
    public void onBackPressed() {
        HeNanSurfaceViewCameraActivity.this.finish();

        super.onBackPressed();

    }

    // 由于图片的质量过高，无法回传数据，现在需要在这里处理图片然后上传
    private byte[] minData(byte[] data) {
        // 将data转换成bitmap，缩小bitmap的尺寸，然后再次转为data上传
        Bitmap oldimgeBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        Bitmap imgeBitmap = bitmapNewWaH(oldimgeBitmap);// 获取新的bitmap
        // 将新的bitmap转为data
        byte[] bitmaptoBytes = BitmaptoBytes(imgeBitmap);
        return bitmaptoBytes;
    }

    //TODO 修改为传输sd卡的路径，在AccidentLoadingPictureView的onresult中处理
    public void sendImage(String path) {
        // byte[] data1=minData(data);//将data压缩以便传输
        Intent intent = new Intent();
        Bundle b = new Bundle();
        b.putString("image", path);
        intent.putExtras(b);
        this.setResult(HeNanSurfaceViewCameraActivity.RESULT_OK, intent);
        this.finish();
    }
    /*public void sendImage(byte[] data)
    {
        // byte[] data1=minData(data);//将data压缩以便传输
        Intent intent = new Intent();
        Bundle b = new Bundle();
        b.putByteArray("image", data);
        intent.putExtras(b);
        this.setResult(HeNanSurfaceViewCameraActivity.RESULT_OK, intent);
        this.finish();
    }*/

    public int getMidX() {
        return midX;
    }

    public void setMidX(int midX) {
        this.midX = midX;
    }

    public int getMidY() {
        return midY;
    }

    public void setMidY(int midY) {
        this.midY = midY;
    }

    // 获取bitmap的宽高，将宽度设为640，高度以倍数缩小，然后设置到bitmap中
    private Bitmap bitmapNewWaH(Bitmap imgeBitmap2) {
        int oldWidth = imgeBitmap2.getWidth();
        int oldHeight = imgeBitmap2.getHeight();
        // 获取新的宽高
        int times = oldWidth / 640;
        int width = 640;
        int height = oldHeight / times;
        // 计算缩放比例
        // 计算缩放比例
        float scaleWidth = ((float) width) / oldWidth;
        float scaleHeight = ((float) height) / oldHeight;
        // 想要缩放的宽高
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newbitmap = Bitmap.createBitmap(imgeBitmap2, 0, 0, oldWidth, oldHeight, matrix, true);
        Log.e("test", newbitmap.getWidth() + ":" + newbitmap.getHeight());
        return newbitmap;
    }

    // bitmap转byte[]
    private byte[] BitmaptoBytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();
    }
}
